import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import getuser from '../../../atoms/getuser';
import { tbpteam } from '../../../atoms/db';

const logger = anylogger('pages/api/team/query.api');

export type IData = Pick<ITbpteam, 'team_id' | 'teamname'>;

export type Result = {
	count: number;
	data: IData[];
};

export type Query = {
	q: string;
	page: string;
	pagesize: string;
}

/**
 *团队查询
 */
const handler = an48<Result>();

handler.get(async (req, res) => {
	try {
		logger.debug('msg query:', req.query);
		const { q, ...rest } = req.query as Query;
		const page = Number(rest.page || '1');
		const pagesize = Number(rest.pagesize || '10');

		const user = await getuser(req);
		if (!user || user.role !== 'admin') {
			res.status(200).json({
				count: 0,
				data: []
			});
			return;
		}
		const dt1 = tbpteam();
		if (q) {
			const query = q.trim();
			dt1.where('projectname', 'like', `%${query}%`)
				.orWhere('projectnumber', 'like', `%${query}%`);

		}
		const [{ size }] = await dt1.count('*', { as: 'size' });
		const count = Number(size);
		const dt2 = tbpteam();
		if (q && typeof q === 'string') {
			const query = q.trim();
			dt2.where('projectname', 'like', `%${query}%`)
				.orWhere('projectnumber', 'like', `%${query}%`);
		}
		const offset = (page - 1) * pagesize;
		const d = await tbpteam()
			.select('projectname', 'projectnumber', 'teamname', 'grade', 'class', 'major', 'teamname', 'id')
			.limit(pagesize)
			.offset(offset)
			.orderBy('projectnumber', 'asc');
		const data = d.map((it) => {
			return {
				...it
			} as IData;
		});
		res.status(200).json({ data, count });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({
			count: 0,
			data: []
		});
	}
});

export const config = {} as PageConfig;

export default handler;
